/**
 * Copyright 2015-2016 eyaomall.cn
 * All rights reserved.
 *
 * @project
 * @author pro
 * @version 1.0
 * @date 2016-03-07
 */
package com.eyaomall.wxmall.common.util;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eyaomall.wxmall.model.pojo.ResAccessToken;
import com.eyaomall.wxmall.model.pojo.ResUserInfo;
import com.eyaomall.wxmall.model.pojo.ResWxUser;
import com.lycheeframework.core.common.util.JSONUtil;

/**
 * 微信工具类
 * @author pro
 *
 */
public class WChatUtil {
	
	private static final Logger LOG = LoggerFactory.getLogger(WChatUtil.class);
	
	/**
	 * 获取accessToken
	 * @param url
	 * @return
	 */
	public static ResAccessToken getUser(String url){
		String response = getResponse(url);
		LOG.error("response json :" + response);
		if(StringUtil.isEmpty(response)) return null;
		
		return JSONUtil.toBean(response, ResAccessToken.class);
	}
	
	/**
	 * 网页认证方式获取微信用户基本信息
	 * @param accessToken
	 * @param openId
	 * @return
	 */
	public static ResWxUser getAccessToken(String accessToken,String openId){
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
		
		String json = getResponse(url);
		LOG.error("response json :" + json);
		if(StringUtil.isEmpty(json)) return null;
		
		return JSONUtil.toBean(json, ResWxUser.class);
	}
	
	/**
	 * 获取我的基本信息
	 * @param token
	 * @param openId
	 * @return
	 */
	public static ResUserInfo getUserInfo(String token,String openId){
		String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "&openid=" + openId + "&lang=zh_CN";
		
		String json = getResponse(url);
		LOG.error("response json :" + json);
		if(StringUtil.isEmpty(json)) return null;
		
		return JSONUtil.toBean(json, ResUserInfo.class);
	}
	
	/**
	 * 获取网络请求结果
	 * @param url
	 * @return
	 */
	protected static String getResponse(String url){
		try {
			HttpClient client = HttpClientBuilder.create().build();
			
			HttpGet get = new HttpGet(url);
			HttpResponse response = client.execute(get);
			if(response.getStatusLine() != null && response.getStatusLine().getStatusCode() == 200){
				return EntityUtils.toString(response.getEntity(),"UTF-8");
			}
			
			return null;
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
			return null;
		} 
	}
	
	public static void main(String[] args) {
		WChatUtil.getAccessToken("WPMVV3WvSYGCw20WYQVYgjk0MNQdnf2h_e8Vx_rGxr9JuhL3yY9LxTSDZXiRDWTL7EQToQfH9EtB9FoS06wfTxV1cecdPvlkestbAjgsed0", "oaKr8v0y9Pb4NVBMiL5OSutFc_hw");
	}
}
